<?php
/**
 * wap2.0 购物流程 - 商品加入购物袋
 */

//var_dump($_POST);exit;

/* 加载json */
include_once( ROOT_PATH . 'includes/cls_json.php');
$json = new JSON;

// 原购物袋
$cartObj = empty($_POST['obj']) ? '' : ($_POST['obj']);

// 要添加的商品
$addGoods = $_POST['cart'];

$goods_added = false;

foreach ($cartObj AS $key => $val){
	if ($val['product_id'] == $addGoods['product_id'] && $val['prop'] == $addGoods['prop']){
		$cartObj[$key]['num'] += $addGoods['num'];
		$goods_added = true;
	}
}

if (!$goods_added){
	$cartObj[] = $_POST['cart'];
}

die($json->encode($cartObj));


/* 获取传递参数 */
$product_id 	= empty($_REQUEST['product_id']) ? 0 : intval($_REQUEST['product_id']);
$num 			= empty($_REQUEST['num']) ? 0 : intval($_REQUEST['num']);
$sku_id 		= empty($_REQUEST['size']) ? 0 : intval($_REQUEST['size']);

$channel_id 	= empty($_REQUEST['channel_id']) ? 0 : intval($_REQUEST['channel_id']);
$cat_id 		= empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
$warehouse 		= empty($_REQUEST['warehouse']) ? '' : trim($_REQUEST['warehouse']);
$product_name 	= empty($_REQUEST['product_name']) ? '' : trim($_REQUEST['product_name']);
$small_image 	= empty($_REQUEST['small_image']) ? '' : trim($_REQUEST['small_image']);
$sexmall_price 	= empty($_REQUEST['sexmall_price']) ? 0 : trim($_REQUEST['sexmall_price']);
$market_price 	= empty($_REQUEST['market_price']) ? 0 : trim($_REQUEST['market_price']);
$agio 			= empty($_REQUEST['agio']) ? '' : trim($_REQUEST['agio']);

// 是否ajax提交
$ajax 			= empty($_REQUEST['ajax']) ? 0 : intval($_REQUEST['ajax']);
$back_url 		= empty($_REQUEST['back_url']) ? '' : trim(urldecode($_REQUEST['back_url']));



$result = array('error'=>0, 'text'=>'', 'url'=>'', 'count'=>0, 'amount'=>0);

/* 加入购物袋 检查登录 */
$user_token = get_user_token();
if (empty($user_token))
{
	$params = array(
		'm'				=> 'flow',
		'act'			=> 'addtocart',
		'product_id'	=> $product_id,
		'num'			=> $num,
		'size'			=> $sku_id,
		'back_url'		=> $back_url,
	);

	if (isAjax())
	{
		$params['ajax'] = 1;
		$back_act = 'index.php?' . http_build_query($params);
		wap_setcookie("WAP[back_act]", urlencode($back_act), 7200);

		$result = array('error'=>-1, 'text'=>'', 'url'=>'user-login.html');
		die($json->encode($result));
	}
	else
	{
		$back_act = 'index.php?' . http_build_query($params);
		wap_setcookie("WAP[back_act]", urlencode($back_act), 7200);

		wap_header("Location: index.php?m=user&act=login");
	}
}

/* 加入成功的跳转链接 */
//$back_act = 'index.php?m=product&product_id='.$product_id.'&act=intro';
$back_act = $back_url;

/* 取得商品尺码信息 */
$leavings = 0;
$goods = array();
$skuInfo = get_product_sku($product_id, false, false, 1);
$productSku = $skuInfo['sku'];

if (!empty($productSku))
{
	foreach ($productSku AS $val)
	{
		if ($val['sku_id'] == $sku_id){
			$goods = $val;
		}
		$leavings += $val['leavings'];
	}
}

/* 检查商品库存数量 */
if ($goods['leavings'] < 1 || $goods['leavings'] < $num || empty($sku_id))
{
	if (isAjax())
	{
		$result = array('error'=>1, 'text'=>'商品库存不够，购买失败！', 'url'=>'');
		die($json->encode($result));
	}
	else
	{
		show_message('商品库存不够，购买失败！', '返回', $back_act, 'warning');
	}
}

/* 商品秒杀免邮活动, 检查加入购物袋的数量是否>限购数量 */
$limit_num=getSeckActivityLimitNum($product_id,$goods['brand_id']);
if ($limit_num>-1){
	if ($limit_num>0 && $num > $limit_num)
	{
		if (isAjax())
		{
			$result = array('error'=>1, 'text'=>'购买失败，该商品限购'.$limit_num.'件', 'url'=>'');
			die($json->encode($result));
		}
		else
		{
			show_message('购买失败，该商品限购'.$limit_num.'件', '返回', $back_act, 'warning');
		}
	}
}


/* 获取加入之前的购物袋
 * 用户点击“立即购买”时，删除购物袋中已加入的同一商品 */
$original_count = $original_num = $new_num = $seckill_goods_num = 0;
$cart_info = get_cart($user_token);

foreach ($cart_info['orders_detail'] AS $key => $val)
{
	// 订单 商品处理
	foreach ($val['order_goods'] AS $k => $v)
	{
		if ($limit_num>-1){
			if ($v['product_id'] == $product_id && $limit_num>0){
				$seckill_goods_num += $v['num'];
			}
		}

		if ($v['product_id'] == $product_id && $v['sku_id'] == $sku_id)
		{
			// 立即购买删除原有该商品
			if (!isAjax())
			{
				$mInterface->deleteShopCart($v['cart_id'], $user_token);
				$seckill_goods_num=0;
			}
			else
			{
				$original_num = $v['num'];
			}
		}
		//$original_count += $v['num'];
	}
}

// 商品秒杀免邮活动, 检查已放入购物袋的数量+要加入的数量是否>限购数量
$limit_num=getSeckActivityLimitNum($product_id,$goods['brand_id']);
if ($limit_num>-1){
	if ($limit_num>0 && ($num + $seckill_goods_num > $limit_num)){
		if (isAjax())
		{
			$result = array('error'=>1, 'text'=>'购买失败，该商品限购'.$limit_num.'件', 'url'=>'');
			die($json->encode($result));
		}
		else
		{
			show_message('购买失败，该商品限购'.$limit_num.'件', '返回', $back_act, 'warning');
		}
	}
}


/* 加入购物袋 */
$cart_info = $mInterface->addShopCart($user_token, $goods['sku_id'], $num);

$mem->addCache('cart_info', '');

// 商品加入后，购物袋的金额、数量
$added_goods = array();
$total = array('count'=>0, 'amount'=>0);
foreach ($cart_info AS $key => $val)
{
	$total['count'] += $val['num'];
	$total['amount'] += $val['num'] * $val['sexmall_price'];

	if ($val['product_id'] == $product_id && $val['sku_id'] == $sku_id)
	{
		$new_num = $val['num'];
		$added_goods = $val;
	}
}

/* 新加入的数量(购物袋新的 - 原来的数量) */
$add_num = $new_num - $original_num;

// 最后加入购物袋商品所属品牌
wap_setcookie("WAP[brd_lst_addtocart]", $goods['brand_id'], 7200);

//插入排行榜
$now = local_time();

// 更新购物袋清空时间
wap_setcookie("WAP[shop_time]", $now, 7200);

if ($product_id)
{
	// 获得品牌
	$brand = get_brand($goods['brand_id']);

	// 记录用户 购物行为
	$data = array(
		'channel_id'	=> $channel_id,
		'product_id'	=> $product_id,
		'brand_id'		=> $brand['brand_id'],
		'brand_name'	=> $brand['brand_name'],
		'cat_id'		=> $cat_id,
		'warehouse'		=> $warehouse,
		'product_name'	=> $product_name,
		'small_image'	=> $small_image,
		'sexmall_price'	=> $sexmall_price,
		'market_price'	=> $market_price,
		'agio'			=> $agio,
		'leavings'		=> $leavings
	);
	user_product_action($data, 1);
}


$clear_time_notice = '';
$clear_time = CART_EXPIRE;
if ($clear_time)
{
	$clear_time_notice = floor($clear_time / 60).'分'.($clear_time % 60).'秒';
}

/* OMNITURE 统计  */
include 'omniture/flow_addtocart.php';

/* 返回输出 */
if (isAjax())
{
	// 同一商品最多加入2件
	if ($add_num < 1 && $original_num > 0 && ($original_num + $num) > 2)
	{
		$result = array(
			'error'			=> 2,
			'text'			=> '加入购物袋失败：同一商品每次最多只能购买2件',
			'url'			=> '',
			'clear_time'	=> $clear_time_notice,
			'count'			=> $total['count'],
			'amount'		=> $total['amount'],
			'add_num'		=> $add_num,
		);
	}
	// 库存不够
	else if ($add_num < 1 && $original_num < 1)
	{
		$result = array(
			'error'			=> 1,
			'text'			=> '商品库存不够，购买失败！',
			'url'			=> ''
			);
	}
	// 加入成功
	else
	{
		$result = array(
			'error'			=> 0,
			'text'			=> '',
			'url'			=> 'flow-cart.html',
			'clear_time'	=> $clear_time_notice,
			'count'			=> $total['count'],
			'amount'		=> $total['amount'],
			'add_num'		=> $add_num,
			'om_act_url'	=> $om_act_url
		);
	}

	die($json->encode($result));
}
else
{
	if ($add_num < 1 && $original_num < 1){
		show_message('商品库存不够，购买失败！', '返回', $back_act, 'warning');
	}

	wap_setcookie('om_act_url', $om_act_url, 7200);

	// 未登录时加入购物袋，登录后的返回链接
	if ($ajax)
	{
		wap_header("Location: ". ($back_act));
	}

	wap_header("Location: index.php?m=flow&act=cart");
}